/**
 * 文件说明 - 模板文件
 */

import { debounce } from "@/utils";
import { CSSProperties, useCallback, useEffect, useRef, useState } from "react";

interface Props {
  className?: string;
  style?: CSSProperties;
  itemHeight?: number; // 每个item的高度
  containerHeight?: number; // 外部窗口的高度
  bufferIndex?: number; // 缓冲数量（这里暂不实现）
  onLoadMore?: (sInd: number, eInd: number) => void;
  [key: string]: any;
}

let pageSize = 0; // 一屏显示多少个元素
let isAutoScroll = true;
let isPressLeftMouse = false; //是否按住了鼠标左键
export default ({
  className = "",
  style,
  itemHeight = 48,
  containerHeight = innerHeight,
  children,
  onLoadMore,
  ...restProps
}: Props) => {
  if (!pageSize) pageSize = Math.floor(containerHeight / itemHeight);
  const scrollRef = useRef(null);
  const [paddingTop, setPaddingTop] = useState(0);
  useEffect(() => {
    if (children?.length < pageSize) setPaddingTop(0);
  }, [children]);
  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    if (isAutoScroll && !isPressLeftMouse) return;
    let { scrollTop: top } = e.currentTarget;
    const sInd = Math.floor(top / itemHeight);
    const eInd = sInd + pageSize;
    onLoadMore?.(sInd, eInd);
    setPaddingTop(sInd * itemHeight);
  };
  const handleWheel = useCallback(
    debounce(
      (e: React.UIEvent<HTMLDivElement>) => (isAutoScroll = true),
      false,
      500
    ),
    []
  );
  useEffect(() => {
    onLoadMore?.(0, Math.floor(containerHeight / itemHeight));
  }, []);
  return (
    <div
      className={`${className} f-fs-s-c`}
      style={{ overflow: "auto", ...style }}
      onScroll={handleScroll}
      onWheel={(e) => {
        isAutoScroll = false;
        handleWheel(e);
      }}
      onMouseDown={(e) => (isPressLeftMouse = e.button === 0)}
      onMouseUp={() => (isPressLeftMouse = false)}
      {...restProps}
      ref={scrollRef}
    >
      <div style={{ paddingTop: `${paddingTop}px` }}>
        {!!children?.length ? (
          children
        ) : (
          <div className="f-c-c pt-32" style={{ color: "#999" }}>
            ~无匹配结果~
          </div>
        )}
      </div>
    </div>
  );
};
